import {Directive, ElementRef, HostListener, Input, Output, EventEmitter} from "@angular/core";
import {UserRegisterHttpService} from "../shared/service/user-register-http.service";
import {CommonHelper} from "../../shared/helper/common-helper";
import {ResponseMsgModel} from "../shared/model/response-msg-model";
import {ResultEntity} from "../../shared/model/resultEntity";
import {ValidateResultMsg} from "../../shared/helper/validateResultMsg";
import {VerifyCommon} from "./verify-common";

@Directive({
    selector: '[usernameValidator]'
})
export class VerifyUsernameDirective extends VerifyCommon {
    @Input() usernameValidator: any;
    @Output() verifyResponse: EventEmitter<ResponseMsgModel> = new EventEmitter<ResponseMsgModel>();

    constructor(el: ElementRef, private userRegisterHttpService: UserRegisterHttpService) {
        super();
    }

    /**
     * 当用户名输入框失去焦点时触发该方法。
     * 校验的情况有：
     * 1）不为空
     * 2）将用户名发往后台校验用户名是否已存在
     */
    @HostListener("blur") onBlur() {
        this.usernameValidator = CommonHelper.trim(this.usernameValidator);
        if (!this.usernameValidator) {
            this.responseComponent(false, "用户名不能为空");
        } else if (this.usernameValidator.length > 12 || this.usernameValidator < 6) {
            this.responseComponent(false, "用户名长度不得少于6位或大于12位");
        } else {
            this.userRegisterHttpService.checkUsernameInRemote(this.usernameValidator, result => this.checkCallback(result));
        }
    }

    private checkCallback(resultEntity: ResultEntity) {
        let resultBool = <string>resultEntity.result === ValidateResultMsg.SUCCESS;
        this.responseComponent(resultBool, resultBool ? "成功" : "用户名已存在");
    }

    getResponseEmitter(): EventEmitter<ResponseMsgModel> {
        return this.verifyResponse;
    }
}